package com.maxlen.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import com.maxlen.common.to.es.SkuEsModel;
import com.maxlen.search.constant.EsConstant;
import com.maxlen.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private ElasticsearchClient client;

    /**
     * 首页查询检索
     * @param skuEsModelList
     * @return
     * @throws IOException
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {

        BulkRequest.Builder br = new BulkRequest.Builder();

        for (SkuEsModel skuEsModel : skuEsModelList) {
            System.out.println(skuEsModel);
            br.operations(op -> op
                    .index(idx -> idx
                            .index(EsConstant.PRODUCT_INDEX)
                            .id(skuEsModel.getSkuId().toString())
                            .document(skuEsModel)
                    )
            );
        }

        BulkResponse bulk = client.bulk(br.build());

        if (bulk.errors()) {
            log.error("Bulk had errors");
            for (BulkResponseItem item: bulk.items()) {
                if (item.error() != null) {
                    log.error("商品上架错误：{}",item.id());
                }
            }
            return false;
        }
        return true;
    }
}
